package com.ego.user.controller;

import com.ego.user.pojo.User;
import com.ego.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkUserData(@PathVariable("data") String data, @PathVariable("type") Integer type) {
        Boolean result = userService.check(data, type);
        if (result == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return ResponseEntity.ok(result);
    }

    @GetMapping("/queryUserByUP")
    public User queryUserByUP(@RequestParam("username") String username, @RequestParam("password")String password) {
        return userService.findByUP(username, password);
    }

    @PostMapping("/send")
    public ResponseEntity<Void> send(@RequestParam("phone") String phone) {
        userService.send(phone);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult bs, @RequestParam("code") String code) {
//        if (bs.hasErrors()) {
//            List<ObjectError> allErrors = bs.getAllErrors();
//            allErrors.forEach(er -> {
//                System.out.println(er.getDefaultMessage());
//            });
//        }
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
}
